package com.qyhl.module_activities.act.player.newlist;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.tools.ScreenUtils;
import com.qyhl.module_activities.R;
import com.qyhl.module_activities.R2;
import com.qyhl.module_activities.act.player.detail.PlayerDetailActivity;
import com.qyhl.module_activities.act.player.list.PlayerListContract;
import com.qyhl.module_activities.act.player.list.PlayerListPresenter;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.entity.act.PlayerVOBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

public class PlayerNewListFragment extends BaseFragment implements PlayerListContract.PlayerListView {
    @BindView(R2.id.player_list_recyle)
    RecyclerView mPlayerListRecyle;
    @BindView(R2.id.player_list_refresh)
    SmartRefreshLayout mPlayerListRefresh;
    @BindView(R2.id.player_list_loading)
    LoadingLayout mPlayerListLoading;
    @BindView(R2.id.participant)
    TextView participant;
    @BindView(R2.id.votenum)
    TextView votenum;
    @BindView(R2.id.amountnum)
    TextView amountnum;
    @BindView(R2.id.sorttext)
    TextView sorttext;
    @BindView(R2.id.edit_search)
    EditText edit_search;
    @BindView(R2.id.search_clear)
    ImageView search_clear;
    @BindView(R2.id.sortimg)
    ImageView sortimg;
    @BindView(R2.id.top_layout)
    RelativeLayout topLayout;
    private static final String TYPE_VOTE_HIGH = "1";
    private static final String TYPE_VOTE_SHORT = "2";
    private String type = TYPE_VOTE_HIGH;
    /**
     * 控制器
     */
    private PlayerListPresenter mPresenter;
    /**
     * 页数
     */
    private int page = 1;

    private String lastPlayerId;
    /**
     * 活动数据
     */
    private int actId;
    private int sumPlayer;
    /**
     * 票数
     */
    private int voteNum;
    /**
     * 至少投票数
     */
    private int perMinVote;
    /**
     * 至少投人数
     */
    private int perReceiver;

    private int sumVote;
    private long pageViews;
    private boolean isHideTop;
    private boolean listEnable = true;

    //展示的数据
    private List<PlayerVOBean> mDataPlayer = new ArrayList<>();

    //存储的数据，用于从查询状态恢复
    private List<PlayerVOBean> sortPlayer = new ArrayList<>();
    /**
     * 适配器
     */
    private CommonAdapter<PlayerVOBean> mAdapter;
    /**
     * 当前状态是否是搜索状态
     */
    private boolean isSearch = false;

    /**
     * 最多可投人数 =  票数（voteNum） /至少投给每个选手多少票(perMinVote)
     */
    private int maxVoteNum = 0;


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_fragment_player_list, container, false);
    }

    public static PlayerNewListFragment newInstance(int actId, Long pageViews, Integer sumPlayer, Integer sumVote, Integer voteNum, Integer perMinVote, Integer perReceiver) {
        PlayerNewListFragment fragment = new PlayerNewListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("actId", actId);
        bundle.putLong("pageViews", pageViews);
        bundle.putInt("sumPlayer", sumPlayer);
        bundle.putInt("sumVote", sumVote);
        bundle.putInt("voteNum", voteNum);
        bundle.putInt("perMinVote", perMinVote);
        bundle.putInt("perReceiver", perReceiver);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static PlayerNewListFragment newInstance(int actId, Long pageViews, Integer sumPlayer, Integer sumVote, Integer voteNum, Integer perMinVote, Integer perReceiver, boolean isHideTop) {
        PlayerNewListFragment fragment = new PlayerNewListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("actId", actId);
        bundle.putLong("pageViews", pageViews);
        bundle.putInt("sumPlayer", sumPlayer);
        bundle.putInt("sumVote", sumVote);
        bundle.putInt("voteNum", voteNum);
        bundle.putInt("perMinVote", perMinVote);
        bundle.putInt("perReceiver", perReceiver);
        bundle.putBoolean("isHideTop", isHideTop);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void create() {
        actId = getArguments().getInt("actId");
        sumVote = getArguments().getInt("sumVote");
        sumPlayer = getArguments().getInt("sumPlayer");
        voteNum = getArguments().getInt("voteNum");
        perMinVote = getArguments().getInt("perMinVote");
        perReceiver = getArguments().getInt("perReceiver");
        pageViews = getArguments().getLong("pageViews");
        isHideTop = getArguments().getBoolean("isHideTop", false);
        mPresenter = new PlayerListPresenter(this);
    }

    @Override
    protected void setListener() {

    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected void onFirstVisible() {
        initView();
    }

    private void initView() {
        BusFactory.getBus().register(this);
        maxVoteNum = voteNum / perMinVote;
        votenum.setText(String.valueOf(sumVote));
        participant.setText(String.valueOf(sumPlayer));
        amountnum.setText(String.valueOf(pageViews));
        lastPlayerId = "0";
        if (isHideTop) {
            topLayout.setVisibility(View.GONE);
            mPresenter.getPlayerListByTime(actId + "", lastPlayerId, "2");
        } else {
            topLayout.setVisibility(View.VISIBLE);
            mPresenter.getData(actId + "", page + "", type);
        }


        mPlayerListLoading.setStatus(LoadingLayout.Loading);

        mPlayerListRefresh.setEnableLoadMore(true);
        mPlayerListRefresh.setEnableRefresh(false);
        mPlayerListRefresh.setDisableContentWhenRefresh(true);
        mPlayerListRefresh.setRefreshFooter(new ClassicsFooter(getContext()));
        mPlayerListRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshlayout) {
                if (isHideTop) {
                    mPresenter.getPlayerListByTime(actId + "", lastPlayerId, "2");
                } else {
                    mPresenter.getData(actId + "", page + "", type);
                }
            }
        });
        mPlayerListRecyle.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

        mPlayerListRecyle.setAdapter(mAdapter = new CommonAdapter<PlayerVOBean>(getContext(), R.layout.act_item_new_act_player, mDataPlayer) {
            @Override
            protected void convert(ViewHolder holder, final PlayerVOBean bean, final int position) {
                //头像
                ImageView image = holder.getView(R.id.player_avatar);
                ViewGroup.LayoutParams params = image.getLayoutParams();
                params.height = getRandomHeight(bean);
                Glide.with(mContext)
                        .load(bean.getPlayer().getApplyUrl())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default))
                        .into(image);

                holder.setText(R.id.player_name, bean.getPlayer().getPlayerName());

                TextView vote_tickets = holder.getView(R.id.player_tickets);
                Typeface fontFace = Typeface.createFromAsset(getContext().getAssets(),
                        "fonts/ReductoCondSSK.ttf");
                vote_tickets.setTypeface(fontFace);
                vote_tickets.setText(String.valueOf(bean.getVoteNumber()));

                ImageView status = holder.getView(R.id.player_status);
                if (bean.getIsSelected() == 0) {
                    status.setImageResource(R.drawable.act_player_selected_off_icon);
                } else {
                    status.setImageResource(R.drawable.act_player_selected_on_icon);
                }

                if (isSearch) {
                    status.setVisibility(View.GONE);
                } else {
                    status.setVisibility(View.VISIBLE);
                }

                status.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int selectedVoteNum = 0;
                        for (int i = 0; i < mDataPlayer.size(); i++) {
                            if (mDataPlayer.get(i).getIsSelected() == 1) {
                                selectedVoteNum++;
                            }
                        }

                        if (bean.getIsSelected() == 0) {
                            if (selectedVoteNum < maxVoteNum) {
                                bean.setIsSelected(1);
                                mAdapter.notifyItemChanged(position);
                            } else {
                                new OtherDialog.Builder(getActivity())
                                        .setContentView(R.layout.act_dialog_new_vote_tips)
                                        .setText(R.id.tips, "最多只能为" + maxVoteNum + "位选手投票哦～")
                                        .setCanceledOnTouchOutside(false)
                                        .setDismissButton(R.id.cancel)
                                        .show();
                            }

                        } else {
                            bean.setIsSelected(0);
                            mAdapter.notifyItemChanged(position);
                        }
                    }
                });
            }
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (listEnable) {
                    listEnable = false;
                    PlayerVOBean player = mAdapter.getDatas().get(position);
                    int playerId = player.getPlayer().getId();
                    Bundle bundle = new Bundle();
                    bundle.putInt("playerId", playerId);
                    bundle.putInt("actId", actId);
                    bundle.putInt("width", player.getApplyCoverWidth());
                    bundle.putInt("height", player.getApplyCoverHeight());
                    bundle.putBoolean("isNew", true);
                    bundle.putString("applyImage", player.getPlayer().getApplyUrl() + "");
                    Intent intent = new Intent(getActivity(), PlayerDetailActivity.class);
                    ActivityOptionsCompat options = ActivityOptionsCompat
                            .makeSceneTransitionAnimation(getActivity(),
                                    view.findViewById(R.id.player_avatar), "applyImg");
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 888, options.toBundle());
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        edit_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
                }
            }
        });

        edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = edit_search.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    restore();
                } else {
                    search_clear.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 888 && resultCode == 555) {
            listEnable = true;
        }
    }

    /**
     * 时间订阅
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dovote(Event.DoVote event) {
        if (event != null) {
            checkVote();
        }
    }


    /**
     * 检测
     */
    public void checkVote() {
        int selectedVoteNum = 0;
        List<PlayerVOBean> selectList = new ArrayList<>();
        for (int i = 0; i < mDataPlayer.size(); i++) {
            if (mDataPlayer.get(i).getIsSelected() == 1) {
                selectedVoteNum++;
                selectList.add(mDataPlayer.get(i));
            }
        }

        if (selectedVoteNum == 0) {
            Toasty.normal(getContext(), "尚未选择任何选手！").show();
            return;
        }

        if (selectedVoteNum < perReceiver) {
            new OtherDialog.Builder(getActivity())
                    .setContentView(R.layout.act_dialog_new_vote_tips)
                    .setText(R.id.tips, "至少为" + perReceiver + "位选手投票哦~")
                    .setCanceledOnTouchOutside(false)
                    .setDismissButton(R.id.cancel)
                    .show();
            return;
        }


        ActVotePopupWindow actVotePopupWindow = new ActVotePopupWindow(getActivity(), actId + "", selectList, perMinVote, voteNum);
        actVotePopupWindow.showPopupWindow();


    }


    @OnClick({R2.id.search, R2.id.search_clear, R2.id.sortimg, R2.id.sorttext})
    public void onclick(View v) {
        int id = v.getId();
        if (id == R.id.search) {
            sortPlayer.clear();
            sortPlayer.addAll(mDataPlayer);
            String text = edit_search.getText().toString();
            if (!TextUtils.isEmpty(text)) {
                mPlayerListLoading.setStatus(LoadingLayout.Loading);
                mPresenter.searchData(actId + "", text);
                sorttext.setVisibility(View.GONE);
                sortimg.setVisibility(View.GONE);
                isSearch = true;
            }
        } else if (id == R.id.search_clear) {
            edit_search.setText("");
            restore();
        } else if (id == R.id.sortimg) {
            sort();
        } else if (id == R.id.sorttext) {
            sort();
        }
    }

    /**
     * 恢复状态
     */
    private void restore() {
        search_clear.setVisibility(View.GONE);
        sorttext.setVisibility(View.VISIBLE);
        sortimg.setVisibility(View.VISIBLE);
        if (isSearch) {
            isSearch = false;
            mPlayerListRefresh.setEnableLoadMore(true);
            if (sortPlayer.isEmpty()) {
                onEmpty();
            } else {
                mDataPlayer.clear();
                mDataPlayer.addAll(sortPlayer);
                mAdapter.notifyDataSetChanged();
                mPlayerListLoading.setStatus(LoadingLayout.Success);
            }
        }
    }

    /**
     * 排序选择
     */
    private void sort() {
        mPlayerListLoading.setStatus(LoadingLayout.Loading);
        if (type.equals(TYPE_VOTE_HIGH)) {
            type = TYPE_VOTE_SHORT;
            sortimg.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_activeplayer_sorting_icon_min));
        } else {
            sortimg.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_activeplayer_sorting_icon_max));
            type = TYPE_VOTE_HIGH;
        }
        page = 1;
        mPresenter.getData(actId + "", page + "", type);
    }

    /**
     * 时间订阅
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.PlayerListRefresh event) {
        if (event != null) {
            page = 1;
            mPresenter.getData(actId + "", page + "", type);
            votenum.setText(String.valueOf(sumVote + voteNum));
        }
    }


    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    @Override
    public void onError(String string) {
        mPlayerListRefresh.finishLoadMore();

        mPlayerListLoading.setErrorText(string);
        mPlayerListLoading.setReloadButtonText("点击重试");
        mPlayerListLoading.setErrorImage(R.drawable.error_content);
        mPlayerListLoading.setStatus(LoadingLayout.Error);
    }

    @Override
    public void onSuccess(List<PlayerVOBean> data) {
        mPlayerListRefresh.finishLoadMore();
        mPlayerListLoading.setStatus(LoadingLayout.Success);

        if (isHideTop) {
            if (data != null && data.size() > 0) {
                if (lastPlayerId.equals("0")) {
                    mDataPlayer.clear();
                    mDataPlayer.addAll(data);
                } else {
                    mDataPlayer.addAll(data);
                }
                lastPlayerId = data.get(data.size() - 1).getPlayer().getId() + "";
            }
        } else {
            if (page == 1) {
                mDataPlayer.clear();
                mDataPlayer.addAll(data);
            } else {
                mDataPlayer.addAll(data);
            }
            page++;
        }

        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onEmpty() {
        mPlayerListLoading.setErrorText("暂无内容");
        mPlayerListLoading.setReloadButtonText("点击重试");
        mPlayerListLoading.setErrorImage(R.drawable.error_content);
        mPlayerListLoading.setStatus(LoadingLayout.Error);
    }

    @Override
    public void onVoteError(String string) {

    }

    @Override
    public void onVoteSuccess() {

    }

    /**
     * 没有更多数据
     */
    @Override
    public void notData() {
        mPlayerListLoading.setStatus(LoadingLayout.Success);
        mPlayerListRefresh.finishLoadMore();
        Toasty.normal(getContext(), getString(R.string.no_data)).show();
    }

    @Override
    public void onSearchError(String string) {
        mPlayerListLoading.setEmptyText(string);
        mPlayerListLoading.setEmptyImage(R.drawable.error_content);
        mPlayerListLoading.setStatus(LoadingLayout.Empty);
        //禁用下拉加载
        mPlayerListRefresh.setEnableLoadMore(false);
    }

    @Override
    public void onSearchSuccess(List<PlayerVOBean> data) {
        mPlayerListRefresh.finishLoadMore();
        mPlayerListLoading.setStatus(LoadingLayout.Success);
        mDataPlayer.clear();
        mDataPlayer.addAll(data);
        mAdapter.notifyDataSetChanged();
        mPlayerListRefresh.setEnableLoadMore(false);
    }

    private int getRandomHeight(PlayerVOBean playerVOBean) {//得到item的高度
        int imgW = (ScreenUtils.getScreenWidth(getActivity()) - ScreenUtils.dip2px(getActivity(), 20)) / 2;
        int r;
        if (playerVOBean.getApplyCoverWidth() != 0 && playerVOBean.getApplyCoverHeight() != 0) {
            float ratio = (float) playerVOBean.getApplyCoverWidth() / imgW;
            r = (int) (playerVOBean.getApplyCoverHeight() / ratio);
        } else {
            Random random = new Random();
            r = 350 + random.nextInt(200);
        }
        return r;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }
}
